package com.back.network.web.serviceImpl;

import org.apache.tomcat.util.security.MD5Encoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.back.network.netty.dto.AccountDTO;
import com.back.network.web.Utils.StringUtils;
import com.back.network.web.dao.UserDao;
import com.back.network.web.dao.UserTokenDao;
import com.back.network.web.entity.User;
import com.back.network.web.service.UserService;

@Service
public class UserServiceImpl implements UserService {
	@Autowired
	UserDao userDao;
	@Autowired
	UserTokenDao userTokenDao;
	@Value("${com.back.network.domain}")
	String domain;

	@Override
	public boolean login(User user) {
		String pwd = user.getPassword();
		String passwd = MD5Encoder.encode(pwd.getBytes());
		user.setPassword(passwd);
		return userDao.login(user) > 0 ? true : false;
	}

	/** 通过账户密码获取用户信息 **/
	@Override
	public User getUser(User user) {
		return userDao.getUser(user);
	}

	/** 绑定账户id-token-域名 **/
	@Override
	public void saveUserToken(User user, String token) {
		userTokenDao.save(user, token);
	}

	@Override
	public boolean hasToken(String token) {
		return userTokenDao.getCountByToken(token) > 0 ? true : false;
	}

	@Override
	public int getUserPortByDomain(String domain) {
		return userTokenDao.getUserPortByDomain(domain);
	}

	@Override
	public int getUserPortByToken(String token) {

		return userTokenDao.getUserPortByToken(token);
	}

	@Override
	public void saveUserPort(String token, int port) {
		userTokenDao.saveUserPort(token, port);

	}

	@Override
	public String getTokenByPort(int port) {

		return userTokenDao.getTokenByPort(port);
	}

	@Override
	public String getTokenByDomain(String domain) {

		return userTokenDao.getTokenByDomain(domain);
	}

	@Override
	public boolean isExistAccount(AccountDTO accountDTO) {
		return userDao.isExistAccount(accountDTO) > 0 ? true : false;
	}

	@Override
	public boolean isExistEmail(AccountDTO accountDTO) {
		return userDao.isExistEmail(accountDTO) > 0 ? true : false;
	}

	@Override
	public int saveAccount(AccountDTO accountDTO) {
		String api = StringUtils.getRandomString(6) + "." + domain;
		return userDao.save(accountDTO, api);
	}

	@Override
	public void updateStateByEmail(String email) {
		userDao.updateStateByEmail(email);
	}

	@Override
	public String getEmailByAccountOrEmail(String accountOremail) {
		return userDao.getEmailByAccountOrEmail(accountOremail);
	}

	@Override
	public void updatePasswordByEmailOrAccount(String password, String emailOrAccount) {
		userDao.updatePasswordByEmailOrAccount(password, emailOrAccount);
	}

}
